package com.wxyzz.cem.controller;

import com.wxyzz.cem.exception.ImageServiceException;
import com.wxyzz.cem.interceptor.UserInterceptor;
import com.wxyzz.cem.service.interfaces.FileHandler;
import com.wxyzz.cem.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author xclhove
 */
@RestController
@RequestMapping("/image")
public class ImageController {
    @Autowired
    private FileHandler fileHandler;
    
    @PostMapping("upload")
    @UserInterceptor.UserIntercept
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        // 存到本地
        if (file.isEmpty()) {
            throw new ImageServiceException("文件为空！");
        }
        String fileName = fileHandler.upload(file);
        
        return Result.success(fileName);
    }
    
    @GetMapping("{fileName}")
    public void download(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        File file = fileHandler.download(fileName);
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] bytesArray = new byte[(int) file.length()];
        fileInputStream.read(bytesArray);
        response.getOutputStream().write(bytesArray);
    }
}
